package top.lshaci.learning.atguigu.interview3;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * TowSumDemo
 * <p>
 * 力扣两数之和
 * </p>
 *
 * @author lshaci
 * @since 1.0.0
 */
public class TowSumDemo {

    public static void main(String[] args) {
        int[] sums = {2, 7, 11, 15};
        int target = 9;
        int[] towSum1 = towSum1(sums, target);
        System.err.println(Arrays.toString(towSum1));
        int[] towSum2 = towSum2(sums, target);
        System.err.println(Arrays.toString(towSum2));
    }

    private static int[] towSum1(int[] nums, int target) {
        for (int i = 0; i < nums.length; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                if (nums[i] + nums[j] == target) {
                    return new int[]{i, j};
                }
            }
        }
        return null;
    }

    private static int[] towSum2(int[] nums, int target) {
        Integer o;
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            if ((o = map.get(target - nums[i])) != null) {
                return new int[]{o, i};
            }
            map.put(nums[i], i);
        }
        return null;
    }
}
